<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>基础的get请求</title>
</head>
<body>
    <h1>POST请求</h1>
    <form id="form">
        <input type="text" name="name">
        <input type="text"name="age">
        <input type="text"name="sex">
        <button id="btn">提交</button>

    </form>
    <script>
        const oForm=document.getElementById('form')
        const oName=document.querySelector('#form input[name=name]');
        const oAge=document.querySelector('#form input[name=age]');
        const oSex=document.querySelector('#form input[]name=sex');
        const oBtn=document.getElementById('btn')
    oForm.onsubmit=function(){
        //收集表单数据
        const nameValue=oName.value;
        const ageValue=oAge.value;
        const sexValue=oSex.value;
        const xhr=new XMLHttpRequest();
        xhr.open("POST","/adduser?a=1",true);
        //请求体的数据放在send中传递
        //因为请求体类型有和很多,所有发送请求的时候一定要设置请求头的Content-Type类型
        //xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        //xhr.Send(`name=${nameValue}&age=${ageValue}&sex=${sexValue}`);
        xhr.setRequestHeader("Content-Type","applient/json;charset=utf-8")
        xhr.send(JSON.stringify({
            name:nameValue,
            age:ageValue,
            sex:sexValue
        }));
        xhr.onreadystatechange=function(){
            if(xhr.readyState===4&&(xhr.status>=200&&xhr.status<=299)){
                console.log(xhr.responseText);
            }
        }
        return false
    }
  </script>
</body>
</html>